﻿using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

namespace DefaultNamespace
{
    public class UploadAB
    {
        [MenuItem(("AB包工具/上传AB包和对比文件"))]
        private static void UploadAllAbFile()
        {
            DirectoryInfo directoryInfo = Directory.CreateDirectory((Application.dataPath + "/ArtRes/AB/PC/"));
            FileInfo[] fileinfo = directoryInfo.GetFiles();
            foreach (var info in fileinfo)
            {
                if (info.Extension == "" || info.Extension == ".txt")
                {
                    FtpUploadFile(info.FullName, info.Name);
                }
            }

        }

        private async static void FtpUploadFile(string filePath, string fileName)
        {
            await Task.Run(() =>
            {
                //1.创建一个FTP连接 用于上传
                FtpWebRequest req = FtpWebRequest.Create(new Uri("ftp://127.0.0.1//AB/PC/" + fileName)) as FtpWebRequest;
                //2.设置一个通信凭证 这样才能上传
                NetworkCredential n = new NetworkCredential("Neon", "123456");
                req.Credentials = n;
                //3.其它设置
                //  设置代理为null
                req.Proxy = null;
                //  请求完毕后 是否关闭控制连接
                req.KeepAlive = false;
                //  操作命令-上传
                req.Method = WebRequestMethods.Ftp.UploadFile;
                //  指定传输的类型 2进制
                req.UseBinary = true;
                Stream upLoadStream = req.GetRequestStream();
                using (FileStream file = File.OpenRead(filePath))
                {
                    byte[] bytes = new byte[2048];
                    int contentLength = file.Read(bytes, 0, bytes.Length);
                    while (contentLength != 0)
                    {
                        //写入到上传流中
                        upLoadStream.Write(bytes, 0, contentLength);
                        //写完再读
                        contentLength = file.Read(bytes, 0, bytes.Length);
                    }
                    //循环完毕后 证明上传结束
                    file.Close();
                    upLoadStream.Close();
                }
                Debug.Log(fileName + "上传成功");
            });
        }
    }
}